var fs = require("fs")
var os = require("os");
const process = require('process');
// process.exit(1);
const csvParser = require('csv-parser');
const sourceFile = './csv/format.csv';
const tagetFile = './csv/fill.csv';
const { keys } =  require('../config/key.js');

console.log('----- fill start -----');
fs.appendFileSync(tagetFile, keys.join(',') + os.EOL);
let ele = {};
fs.createReadStream(sourceFile)
  .pipe(csvParser())
  .on('data', (data) => {
    if (ele.time) {
      fill(ele, data);
    }
    writeFile(tagetFile, data);
    ele = Object.assign({}, data);
  })
  .on('end', () => {
    console.log('----- fill end -----');
  });
function writeFile(filePath, data) {
    let arr = [];
    keys.forEach(val=>{
      arr.push(data[val]);
    })
    const text = arr.join(',')
	  fs.appendFileSync(filePath, text + os.EOL);
}

function fill(last, cur) {
  const num = Math.ceil(subTime(cur.time, last.time) / 3);
  if(num >= 2) {
    const v1 = sub(cur.fv35, last.fv35);
    const v2 = sub(cur.fv36, last.fv36);
    const step1 = fixNum(v1 / num);
    const step2 = fixNum(v2 / num);
    let row = Object.assign({}, last);
    for (let i=0; i< (num - 1); i++) {
      row.time =  addTime(last.time, 3 * (i+1));
      row.fv35 =  (Number(last.fv35) + step1 * (i+1)).toFixed(2);
      row.fv36 = (Number(last.fv36) + step2 * (i+1)).toFixed(2);
      writeFile(tagetFile, row);
    }
  }
}

function sub(num1, num2) {
  return num1 - num2;
}

function subTime(time1, time2) {
  return ((new Date(time1) - new Date(time2)) / 1000).toFixed(3);
}

function fixNum (num) {
  let str = num.toString();

  let res = '';
  for(let i=0; i<str.length; i++){

    res += str[i];
    if(str[i] !== '0' && str[i] !== '.'){
      break;
    }
  }
  return Number(res);
}

function addTime (time, step) {
  let timetamp = new Date(time).getTime() + step * 1000;
  const date = new Date(timetamp); // 根据时间戳创建Date对象
  const year = date.getFullYear(); // 获取年份
  const month = date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1;
  const day = date.getDate() < 10 ? '0'+ date.getDate()  : date.getDate() ; // 获取日期
  const hour = date.getHours() < 10 ? '0'+ date.getHours()  : date.getHours() ; // 获取小时
  const minute = date.getMinutes() < 10 ? '0'+ date.getMinutes() : date.getMinutes(); // 获取分钟
  const second = date.getSeconds()< 10 ?  '0'+date.getSeconds() : date.getSeconds(); // 获取秒数

  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;

}
